using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Domain.EWE;
using SmartTracking.Infrastructure.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System;

namespace SmartTracking.ApiWrite.Applications.Commands.Ewemating
{
    /// <summary>
    /// 恢复母羊配种数据处理器
    /// </summary>
    public class RestoreEwematingCommandHandler : IRequestHandler<RestoreEwematingCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Ewematings> eRep;

        public RestoreEwematingCommandHandler(IBaseRepository<Ewematings> eRep)
        {
            this.eRep = eRep;
        }

        public async Task<ApiResult<int>> Handle(RestoreEwematingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            if (request.EwematingIdList == null || request.EwematingIdList.Count == 0)
            {
                result.Code = ApiEnum.更新失败;
                result.Message = "参数错误，配种数据ID列表不能为空";
                return result;
            }

            try
            {
                // 获取所有需要恢复的记录（包括已删除的）
                var ids = request.EwematingIdList.Distinct().ToList();
                var existingRecords = eRep.GetAll()
                    .Where(x => ids.Contains(x.EwematingId))
                    .ToList();

                // 验证所有记录是否存在
                var notFoundIds = ids.Except(existingRecords.Select(x => x.EwematingId)).ToList();
                if (notFoundIds.Any())
                {
                    result.Code = ApiEnum.更新失败;
                    result.Message = $"未找到ID为 {string.Join(", ", notFoundIds)} 的配种记录";
                    return result;
                }

                // 验证是否有未删除的记录
                var notDeletedRecords = existingRecords.Where(x => !x.IsDeleted).Select(x => x.EwematingId).ToList();
                if (notDeletedRecords.Any())
                {
                    result.Code = ApiEnum.更新失败;
                    result.Message = $"配种记录 {string.Join(", ", notDeletedRecords)} 未被删除，无需恢复";
                    return result;
                }

                // 恢复数据：将已删除的记录标记为未删除
                var deletedRecords = existingRecords.Where(x => x.IsDeleted).ToList();
                foreach (var record in deletedRecords)
                {
                    record.IsDeleted = false;
                }

                int affectedRows = await eRep.UpdateRangeAsync(deletedRecords);

                if (affectedRows > 0)
                {
                    result.Code = ApiEnum.更新成功;
                    result.Message = $"反填数据成功，共恢复{affectedRows}条记录";
                    result.data = affectedRows;
                }
                else
                {
                    result.Code = ApiEnum.更新失败;
                    result.Message = "反填数据失败，没有记录被恢复";
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.更新失败;
                result.Message = "反填数据过程中发生错误：" + ex.Message;
            }

            return result;
        }
    }
}
